package org.hishenframework.web.validate.jqvalidate;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.ResourceBundle;

public class JqueryValidatorRuleUtil {

	private static final String vmBaseName = "ValidationMessages";
	
	/**
	 * 获取规则
	 * @param annotation
	 * @return
	 */
	public static JqueryValidateRule toRule(Annotation annotation, String jqueryValidatorRule, List<String> params) {
		//是否没有参数
		boolean noParams = params == null || params.size() == 0 ? true : false;   
		Class<?> annotationType = annotation.annotationType();
		String type = null;
		if (jqueryValidatorRule != null) {
			type = jqueryValidatorRule;
		} else {
			type = annotationType.getSimpleName();
			//将首字母转换为小写
			if (type.length() == 1) {
				type = type.substring(0, 1).toLowerCase();
			} else {
				type = type.substring(0, 1).toLowerCase() + type.substring(1, type.length());
			}
		}
		
		StringBuilder valueBuilder = new StringBuilder();
		if (noParams) {
			valueBuilder.append(true);
		}
		
		try {
			Method messageMethod = annotationType.getMethod("message");
			String message = (String) messageMethod.invoke(annotation);
			//判断是否使用ValidationMessages.properties中的消息
			if (message.matches("\\{.*\\}")) {
				String className = message.substring(1, message.length() - 1);
				ResourceBundle rb = ResourceBundle.getBundle(vmBaseName);
				message = rb.getString(className);
			}
			if (!noParams) {
				for (String name : params) {
					Method method = annotationType.getMethod(name);
					Object value = method.invoke(annotation);
					//生成值
					if (value instanceof String || value instanceof Character) {
						valueBuilder.append("\"").append(value).append("\"");
					} else {
						valueBuilder.append(value);
					}
					valueBuilder.append(",");
					//生成消息
					if (message.indexOf("{" + method.getName() + "}") != -1) {
						message = message.replaceAll("\\{" + method.getName() + "\\}", String.valueOf(value));
					}
				}
				valueBuilder.delete(valueBuilder.length() - 1, valueBuilder.length());
				//如果参数超过2个就使用数组
				if (params.size() > 1) {
					valueBuilder.insert(0, "[").append("]");
				}
			}			
			return new JqueryValidateRule(type, valueBuilder.toString(), message);
			
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
}
